﻿using System.Globalization;
using System.IO;
using System.Linq;
using System.Windows;
using System.Collections.Generic;
using XmlStudio.Localization;
using Tomers.WPF.Localization;
using XmlStudio.Interfaces;
using XmlStudio.Settings;
using System;
using Microsoft.Practices.EnterpriseLibrary.ExceptionHandling;
using Microsoft.Practices.EnterpriseLibrary.Logging;
using System.Diagnostics;

namespace XmlStudio {
    /// <summary>
    /// Interaction logic for App.xaml
    /// </summary>
    // ReSharper disable RedundantExtendsListEntry
    public partial class App : Application {
        // ReSharper restore RedundantExtendsListEntry
        #region Fields
        private List<MainWindow> windows = new List<MainWindow>();
        private ApplicationMode applicationMode = ApplicationMode.Xml;
        protected const string DefaultExceptionPolicy = "UIPolicy";
        #endregion

        #region Properties
        public ApplicationMode ApplicationMode { get { return this.applicationMode; } }
        #endregion

        /// <summary>
        /// Occurs on application's startup.
        /// </summary>
        /// <param name="e">The event args.</param>
        protected override void OnStartup(StartupEventArgs e) {
            try {
                Logger.Writer.Write("Starting XmlStudio.", "App", 10, 1, System.Diagnostics.TraceEventType.Error);

                base.OnStartup(e);

                Process pc = Process.GetCurrentProcess();
                Directory.SetCurrentDirectory(pc.MainModule.FileName.Substring(0, pc.MainModule.FileName.LastIndexOf(@"\")));

                string[] languages = Directory.GetFiles("Localization/", "*.xml");

                foreach(string lang in languages) {
                    var fi = new FileInfo(lang);
                    string cultureName = fi.Name.Substring(0, fi.Name.IndexOf(".xml"));
                    var info = CultureInfo.GetCultureInfo(cultureName);
                    LanguageDictionary.RegisterDictionary(info, new XmlLanguageDictionary(fi.FullName));

                    XmlStudioSettings.Instance.Languages.Add(new LanguageSetting { Value = info.Name, DisplayName = info.NativeName });
                }

                // to do: when there is no languagel, set en-US as default
                if(XmlStudioSettings.Instance.Language.Value != null) {
                    LanguageContext.Instance.Culture = CultureInfo.GetCultureInfo(XmlStudioSettings.Instance.Language.Value);
                } else {
                    LanguageContext.Instance.Culture = CultureInfo.GetCultureInfo("en-US");
                }

                if(e.Args.Length > 0) {
                    foreach(var path in e.Args) {
                        var extension = new FileInfo(path).Extension;

                        if(extension == ".xml") {
                            this.applicationMode = ApplicationMode.Xml;
                            var window = new MainWindow(this, path, this.ApplicationMode);
                            window.Show();
                        } else if(extension == ".xsd") {
                            this.applicationMode = ApplicationMode.Xsd;
                            var window = new MainWindow(this, path, this.ApplicationMode);
                            window.Show();
                        }
                    }
                } else {
                    var window = new MainWindow(this, this.ApplicationMode);
                    window.Show();
                }
            } catch(Exception ex) {
                bool rethrow = ExceptionPolicy.HandleException(ex, DefaultExceptionPolicy);
                if(rethrow) {
                    throw;
                }
            }
        }

        public void AddWindow(MainWindow window) {
            this.windows.Add(window);
        }

        public void RemoveWindow(MainWindow window) {
            this.windows.Remove(window);
        }

        public void CloseAllWindows() {
            var toClose = from x in this.windows select x;
            foreach(var window in toClose.ToList()) {
                window.Close();
            }
        }
    }
}